package com.hnkywl.sts.action.kcgl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hnkywl.sts.dao.cggl.CgdDao;
import com.hnkywl.sts.dao.xsgl.ShjDao;
import com.hnkywl.sts.entity.cggl.Cgd;
import com.hnkywl.sts.entity.cggl.Cgdmx;
import com.hnkywl.sts.entity.cggl.search.QueryCgd;
import com.hnkywl.sts.entity.organ.Gsjg;
import com.hnkywl.sts.entity.sys.Gncz;
import com.hnkywl.sts.service.cggl.CgdService;
import com.hnkywl.sts.service.sys.GnczService;
import com.hnkywl.sts.service.sys.YgService;
import net.ruixin.orm.hibernate.Page;
import net.ruixin.web.struts2.SimpleActionSupport;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Namespaces;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: jerry
 * Date: 13-4-15
 * Time: 下午2:17
 * To change this template use File | Settings | File Templates.
 */
@Namespaces({@Namespace("/kcgl/rksh")})
public class RkshAction extends SimpleActionSupport {
    //发货开始时间
    private Date fhrqStart;
    //发货结束时间
    private Date fhrqEnd;
    //采购结算单ID
    private Long cgjsdId;
    //采购单号
    private String cgdh;
    //是否过期
    private Integer sfgq = 1;
    //页面当前位置
    private int page;
    //每页行数
    private int rows;
    //行索引
    private int index;
    private Long khId;

    private Long cggsId;

    private Long cgbmId;

    private Long cgrId;

    private Long gcId;
    private Long cghtId;

    private Long gysid;

    //private String zt;
    private String yrk = "wrk";

    private String sfys;

    private Cgd rksh;

    //查询
    private QueryCgd queryCgd;

    private CgdService cgdService;

    //功能操作
    private List<Gncz> gnczList;
    private GnczService gnczService;

    private Long dhdId;

    private String lx;

    private String wzbm;
    private Date CurrentTime = new Date();
    private String zdr;
    private Long dhck;

    private CgdDao cgddao;
    private ShjDao shjDao;

    @Action("rksh")
    public String rksh() {
        gnczList = gnczService.findGnczByJsAndUrl(request.getServletPath());
        return SUCCESS;
    }

    @Action("rksh_ys")
    public String rkshYs() {
        rksh = this.cgdService.findById(rksh.getId());
        return SUCCESS;
    }

    @Action("check_rksh")
    public void checkRksh() {
        try {
            this.cgdService.check(rksh);
            renderText("{\"statusCode\":\"200\", \"message\":\"验收成功！\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    @Action("cancel_rksh")
    public void cancelRksh() {
        try {
            this.cgdService.cancelRkshYs(rksh);
            renderText("{\"statusCode\":\"200\", \"message\":\"取消验收成功！\", \"operationType\":\"delete\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    @Action("stock_rksh")
    public void stockRksh() {
        try {
            //todo
            this.cgdService.stock(rksh);
            //执行计算赎货价的存储过程
//            for(Cgdmx cgdmx : rksh.getCgdmxList()) {
//                System.out.println(cgdmx.getKh().getId());
//                shjDao.executeShj(cgdmx.getKh().getId());
//            }
            if (sfsy(rksh)) {
                renderText("{\"statusCode\":\"400\",\"cgdid\":" + rksh.getId() + ",\"message\":\"入库成功！\"}");
            } else {
                renderText("{\"statusCode\":\"200\", \"message\":\"入库成功！\"}");
            }

        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    /**
     * 保供类型采购单，判断是否生成补充采购单
     *
     * @param cgd 原采购单
     * @return 需要生成返回true
     */
    private boolean sfsy(Cgd cgd) {
        cgd = this.cgddao.get(cgd.getId());

        boolean result = false;
        //判断是否保供采购
        if (!"bght".equals(cgd.getCglx())) {
            return false;
        }

        //判断是否全部到货
        for (Cgdmx cgdmx : cgd.getCgdmxList()) {
            if (cgdmx.getRksl() >= cgdmx.getSbsl()) continue;
            return true;
        }

        return result;
    }

    /**
     * 采购单列表
     */
    @Action("rkshlist")
    public void rkshlist() {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        Page<Map> cgds = cgdService.findByYtjQuery(dhck, yrk, sfys, lx, cggsId, cgbmId, cgrId, cgdh, wzbm, gysid, fhrqStart, fhrqEnd, sfgq, page, rows);
        String cgdJson = gson.toJson(cgds.getResult());
        this.renderJson("{\"total\":" + cgds.getTotalCount() + ",\"rows\":" + cgdJson + "}");
    }

    /**
     * 采购单
     */
    @Action("rksh_detail")
    public String rkshDetail() {
        zdr = YgService.getCurrentYg().getXm();
        rksh = this.cgdService.findById(rksh.getId());
        return SUCCESS;
    }

    /**
     * 入库判断（根据采购单的申报公司的是否开启到货单入库功能）
     *
     * @return
     */
    @Action(value = "rksh_decideStock",
            results = {
                    @Result(name = "stock", type = "chain", location = "rksh_stock"),
                    @Result(name = "zcstock", type = "chain", location = "rksh_zcstock")
            })
    public String decideRkshStock() {
        Gsjg sbgs = cgdService.findById(rksh.getId()).getSbgs();
        if (sbgs.getSfqydhdrk()) {
            return "stock";
        } else {
            return "zcstock";
        }
    }

    /**
     * 到货单入库
     *
     * @return
     */
    @Action("rksh_stock")
    public String rkshStock() {
        rksh = this.cgdService.findById(rksh.getId());
        return SUCCESS;
    }

    /**
     * 正常入库
     *
     * @return
     */
    @Action("rksh_zcstock")
    public String rkshZcStock() {
        rksh = this.cgdService.findById(rksh.getId());
        return SUCCESS;
    }

    @Action("rksh_cgmx")
    public void rkshCgmx() {
        Gson gson = new Gson();
        List<Map> cgmxs = new ArrayList<Map>();
        List<Map> cgmx = this.cgdService.findCgmx(rksh.getId());
        for (Map map : cgmx) {
            map.put("rkjs", map.get("rkjs"));
            map.put("rksl", map.get("rksl"));
            cgmxs.add(map);
        }
        String result = "{\"rows\":" + gson.toJson(cgmxs) + "}";
        this.renderJson(result);
    }


    @Action("rksh_rkmx")
    public void rkmx() {
        this.renderJson(this.cgdService.findrkmx(rksh.getId()));
    }

    @Action("rksh_rkmxDetail")
    public void rkmxDetail() {
        rksh = this.cgdService.findById(rksh.getId());
        if (rksh.getYrk()) {
            this.renderJson(this.cgdService.findrkmxDetail(rksh.getId()));
        } else {
            Gson gson = new Gson();
            List<Map> cgdmxList = this.cgdService.findCgmx(rksh.getId());
            String json = gson.toJson(cgdmxList);
            this.renderJson("{\"rows\":" + json + "}");
        }
    }

    @Action("rksh_cgfy")
    public void rkshCgfy() {
        Gson gson = new Gson();
        String result = "{\"rows\":" + gson.toJson(this.cgdService.findCgfy(rksh.getId())) + "}";
        this.renderJson(result);
    }

    //采购结算单中查询采购单
    @Action("cgdSearchList")
    public void cgdSearchList() {
        this.renderJson(this.cgdService.findCgdSearch(cgdh, fhrqStart, fhrqEnd, cgjsdId, cggsId, gysid, this.page, this.rows));
    }

    //采购结算单中查询采购单
    @Action("cgdmxSearchList")
    public void cgdmxSearchList() {
        this.renderJson(this.cgdService.findCgdmxSearch(cgjsdId));
    }


    @Action("rkshDetail")
    public void cgdDetail() {
        Gson gson = new Gson();
        List<Map> cgdmxList = this.cgdService.findCgmx(rksh.getId());
        Integer js = 0;
        Double sbsl = 0d;
        Double hsj = 0d;
        Double bhsj = 0d;
        Integer rkjs = 0;
        Double rksl = 0d;
        Double rkjz = 0d;
        Double rkje = 0d;
        String result = "";
        java.text.DecimalFormat df = new java.text.DecimalFormat("0.0000");
        java.text.DecimalFormat jtdf = new java.text.DecimalFormat("0.00");
        StringBuffer sbTable = new StringBuffer();
        if (null != cgdmxList) {
            sbTable.append("<table class=\"tb intb\"><thead>");
            sbTable.append("<tr>");
            sbTable.append("<td style='width:100px;'>物资编码</td><td width='30px'>品名</td><td>规格型号</td><td width='60px'>图号/材质</td><td width='60px'>牌号商标</td>" +
                    "<td width='30px'>单位</td><td width='60px'>应送货数量</td><td width='60px'>已送货数量</td><td>单价(含税)</td><td>总金额(含税)</td>");
            sbTable.append("</tr></thead><tbody>");

            for (int i = 0; i < cgdmxList.size(); i++) {
                sbTable.append("<tr>");
                if (null != cgdmxList.get(i).get("cgd.cglx") && "bght".equals(cgdmxList.get(i).get("cgd.cglx"))) {
                    sbTable.append("<td>");
                    if (null != cgdmxList.get(i).get("wzgg.oldcode")) {
                        sbTable.append(cgdmxList.get(i).get("wzgg.oldcode"));
                    }
                    sbTable.append("</td>");
                } else {
                    sbTable.append("<td>");
                    if (null != cgdmxList.get(i).get("wzgg.code")) {
                        sbTable.append(cgdmxList.get(i).get("wzgg.code"));
                    }
                    sbTable.append("</td>");
                }

                sbTable.append("<td>");
                if (null != cgdmxList.get(i).get("wzgg.name")) {
                    sbTable.append(cgdmxList.get(i).get("wzgg.name"));
                }
                sbTable.append("</td>");

                sbTable.append("<td>");
                if (null != cgdmxList.get(i).get("wzgg.ggxh")) {
                    sbTable.append(cgdmxList.get(i).get("wzgg.ggxh"));
                }
                sbTable.append("</td>");

                sbTable.append("<td>");
                if (null != cgdmxList.get(i).get("th")) {
                    sbTable.append(cgdmxList.get(i).get("th"));
                }
                sbTable.append("</td>");

                sbTable.append("<td>");
                if (null != cgdmxList.get(i).get("cd.z")) {
                    sbTable.append(cgdmxList.get(i).get("cd.z"));
                }
                sbTable.append("</td>");

                sbTable.append("<td>");
                if (null != cgdmxList.get(i).get("wzgg.dw")) {
                    sbTable.append(cgdmxList.get(i).get("wzgg.dw"));
                }
                sbTable.append("</td>");

                sbTable.append("<td>");
                if (null != cgdmxList.get(i).get("sbsl")) {
                    Double msbsl = (Double) cgdmxList.get(i).get("sbsl");
                    BigDecimal bsbsl = new BigDecimal(msbsl);
                    Double dsbsl = bsbsl.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
                    sbTable.append(df.format(dsbsl));
                    sbsl += dsbsl;
                }
                sbTable.append("</td>");

                sbTable.append("<td>");
                if (null != cgdmxList.get(i).get("rksl")) {
                    Double mrksl = (Double) cgdmxList.get(i).get("rksl");
                    BigDecimal brksl = new BigDecimal(mrksl);
                    Double drksl = brksl.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
                    sbTable.append(df.format(drksl));
                    rksl += drksl;
                }
                sbTable.append("</td>");


                sbTable.append("<td>");
                if (null != cgdmxList.get(i).get("hsj")) {
                    sbTable.append(df.format(cgdmxList.get(i).get("hsj")));
                }
                sbTable.append("</td>");

                sbTable.append("<td>");
                if (null != cgdmxList.get(i).get("hsj") && null != cgdmxList.get(i).get("rksl")) {
                    Double mrkje = ((Double) cgdmxList.get(i).get("hsj")) * ((Double) cgdmxList.get(i).get("rksl"));
                    BigDecimal brkje = new BigDecimal(mrkje);
                    Double drkje = brkje.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    sbTable.append(jtdf.format(drkje));
                    rkje += drkje;
                }
                sbTable.append("</td>");

                sbTable.append("</tr>");
            }
            sbTable.append("<tr>");
            sbTable.append("<th colspan=\"6\">合计");
            sbTable.append("</th>");

            sbTable.append("<td>");
            sbTable.append(df.format(sbsl));
            sbTable.append("</td>");

            sbTable.append("<td>");
            sbTable.append(df.format(rksl));
            sbTable.append("</td>");

            sbTable.append("<td>");
            sbTable.append("</td>");

            sbTable.append("<td>");
            sbTable.append(jtdf.format(rkje));
            sbTable.append("</td>");

            sbTable.append("</tr>");
            sbTable.append("</tbody></table>");
        }
        renderHtml(sbTable.toString());
    }

    public Long getDhdId() {
        return dhdId;
    }

    public void setDhdId(Long dhdId) {
        this.dhdId = dhdId;
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }


    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public int getIndex() {
        return index;
    }


    public void setIndex(int index) {
        this.index = index;
    }

    public String getZdr() {
        return zdr;
    }

    public void setZdr(String zdr) {
        this.zdr = zdr;
    }

    public Long getDhck() {
        return dhck;
    }

    public void setDhck(Long dhck) {
        this.dhck = dhck;
    }

    @Autowired
    public void setCgdService(CgdService cgdService) {
        this.cgdService = cgdService;
    }

    public QueryCgd getQueryCgd() {
        return queryCgd;
    }

    public void setQueryCgd(QueryCgd queryCgd) {
        this.queryCgd = queryCgd;
    }

    public String getLx() {
        return lx;
    }

    public void setLx(String lx) {
        this.lx = lx;
    }

    public String getWzbm() {
        return wzbm;
    }

    public void setWzbm(String wzbm) {
        this.wzbm = wzbm;
    }

    public Date getFhrqStart() {
        return fhrqStart;
    }

    public void setFhrqStart(Date fhrqStart) {
        this.fhrqStart = fhrqStart;
    }

    public Date getFhrqEnd() {
        return fhrqEnd;
    }

    public void setFhrqEnd(Date fhrqEnd) {
        this.fhrqEnd = fhrqEnd;
    }

    public Long getCgjsdId() {
        return cgjsdId;
    }

    public void setCgjsdId(Long cgjsdId) {
        this.cgjsdId = cgjsdId;
    }

    public String getCgdh() {
        return cgdh;
    }

    public void setCgdh(String cgdh) {
        this.cgdh = cgdh;
    }

    public Long getKhId() {
        return khId;
    }

    public void setKhId(Long khId) {
        this.khId = khId;
    }

    public Long getCggsId() {
        return cggsId;
    }

    public void setCggsId(Long cggsId) {
        this.cggsId = cggsId;
    }

    public Long getCgbmId() {
        return cgbmId;
    }

    public void setCgbmId(Long cgbmId) {
        this.cgbmId = cgbmId;
    }

    public Long getCgrId() {
        return cgrId;
    }

    public void setCgrId(Long cgrId) {
        this.cgrId = cgrId;
    }

    public Long getGcId() {
        return gcId;
    }

    public void setGcId(Long gcId) {
        this.gcId = gcId;
    }

    public Long getCghtId() {
        return cghtId;
    }

    public void setCghtId(Long cghtId) {
        this.cghtId = cghtId;
    }

    public String getYrk() {
        return yrk;
    }

    public void setYrk(String yrk) {
        this.yrk = yrk;
    }

    public String getSfys() {
        return sfys;
    }

    public void setSfys(String sfys) {
        this.sfys = sfys;
    }

    public Date getCurrentTime() {
        return CurrentTime;
    }

    public void setCurrentTime(Date currentTime) {
        CurrentTime = currentTime;
    }

    public Cgd getRksh() {
        return rksh;
    }

    public void setRksh(Cgd rksh) {
        this.rksh = rksh;
    }

    public Long getGysid() {
        return gysid;
    }

    public void setGysid(Long gysid) {
        this.gysid = gysid;
    }

    public List<Gncz> getGnczList() {
        return gnczList;
    }

    public void setGnczList(List<Gncz> gnczList) {
        this.gnczList = gnczList;
    }

    public Integer getSfgq() {
        return sfgq;
    }

    public void setSfgq(Integer sfgq) {
        this.sfgq = sfgq;
    }

    @Autowired
    public void setGnczService(GnczService gnczService) {
        this.gnczService = gnczService;
    }

    @Autowired
    public void setCgddao(CgdDao cgddao) {
        this.cgddao = cgddao;
    }

    @Autowired
    public void setShjDao(ShjDao shjDao) {
        this.shjDao = shjDao;
    }
}
